<template>
  <div>
    <p>MQTT Message: {{ message }}</p> 
    <el-row :gutter="20">
        <el-col :span="12"><el-input v-model="message" placeholder="请输入内容"></el-input></el-col>
        <el-col :span="12">
            <el-button @click="doPublish" type="success" round>发送消息</el-button>
            <el-button @click="doSubscribe()">订阅b主题</el-button>
            <el-button @click="doUnSubscribe()">取消订阅</el-button>
        </el-col>
    </el-row>

  </div>
</template>
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
<script>
// import mqtt from 'mqtt';
// import mqtt from '../../util/mqtt.min.js'
// import mqtt from '../../util/mqtt3.0.0.js'

export default {
  name: 'HelloWorld',
  data() {
    return {
      message: '',

      connection: {
        protocol: "wss",
        host: "broker.emqx.io",
        // ws: 8083; wss: 8084
        port: 8084,
        endpoint: "/mqtt",
        clean: true,
        connectTimeout: 30 * 1000, // ms
        reconnectPeriod: 4000, // ms
        clientId: "emqx_vue_" + Math.random().toString(16).substring(2, 8),
        // auth
        username: "emqx_test",
        password: "emqx_test",
      },
      subscription: {
        topic: "topicMq/#",
        qos: 0,
      },
      publish: {
        topic: "topicMq/browser",
        qos: 0,
        payload: '{ "msg": "Hello, I am browser." }',
      },
      receiveNews: "",
      qosList: [0, 1, 2],
      client: {
        connected: false,
      },
      subscribeSuccess: false,
      connecting: false,
      retryTimes: 0,
    };
  },
  created() {
    this.createConnection();
  },
  methods: {
    createConnection() {
      try {
        this.connecting = true;
        const { protocol, host, port, endpoint, ...options } = this.connection;
        const connectUrl = `${protocol}://${host}:${port}${endpoint}`;
        const connectUrl_1 = 'wss://broker.emqx.io:8084/mqtt';

        this.client = mqtt.connect(connectUrl_1, options);
        console.log( connectUrl, connectUrl_1 )

        if (this.client.on) {
          this.client.on("connect", () => {
            this.connecting = false;
            console.log("Connection succeeded!");
          });
          this.client.on("reconnect", this.handleOnReConnect);
          this.client.on("error", (error) => {
            console.log("Connection failed", error);
          });
          // 接受消息处理
          this.client.on("message", (topic, message) => {
            this.receiveNews = this.receiveNews.concat(message);
            console.log(`Received message ${message} from ${topic}`);

            this.message = message.toString();
          });
          // 断开
          this.client.on('close', function () {
            console.log('Connection close');
          });
        }
      } catch (error) {
        this.connecting = false;
        console.log("mqtt.connect error", error);
      }
    },
    initData() {
      this.client = {
        connected: false,
      };
      this.retryTimes = 0;
      this.connecting = false;
      this.subscribeSuccess = false;
    },
    // 重连处理
    handleOnReConnect() {
      this.retryTimes += 1;
      if (this.retryTimes > 5) {
        try {
          this.client.end();
          this.initData();
          this.$message.error("Connection maxReconnectTimes limit, stop retry");
        } catch (error) {
          this.$message.error(error.toString());
        }
      }
    },
    // 发布
    doPublish() {
      const { topic, qos, payload } = this.publish
      this.client.publish(topic, payload, { qos, retain: true }, error => {
        if (error) {
          console.log('Publish error', error)
        } else {
          console.log(`Published ${topic}`)
        }
      })
    },
    // 订阅
    doSubscribe() {
      const { topic, qos } = this.subscription
      this.client.subscribe(topic, { qos }, (error, res) => {
        if (error) {
          console.log('Subscribe to topics error', error)
          return
        }
        this.subscribeSuccess = true
        console.log('Subscribe to topics res', res)
      })
    },
    // 取消订阅
    doUnSubscribe() {
      const { topic } = this.subscription
      this.client.unsubscribe(topic, error => {
        if (error) {
          console.log('Unsubscribe error', error)
        }
        console.log('Unsubscribe success')
      })
    },
    // 断开
    destroyConnection() {
      if (this.client.connected) {
        try {
          this.client.end(false, () => {
            this.initData()
            console.log('Successfully disconnected!')
          })
        } catch (error) {
          console.log('Disconnect failed', error.toString())
        }
      }
    }
  },
  beforeDestroy() {
    this.destroyConnection();
    if (this.client) {
      this.client.end();
    }
  }
};
</script>
 
<style>
  /* ... */
</style>